package doan.chuyennganh.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import doan.chuyennganh.base.DoAnBaseAcitvity;
import doan.chuyennganh.base.RequestUI;
import doan.chuyennganh.model.ClassStudent;
import doan.chuyennganh.model.ListClassReturnObject;
import doan.chuyennganh.model.ListStudentReturnObject;
import doan.chuyennganh.model.Student;
import doan.chuyennganh.util.Constants;
import doan.chuyennganh.util.EncodeHelper;
import doan.chuyennganh.util.ListClassDataSource;
import doan.chuyennganh.util.ListStudentDataSource;

public class MainActivity extends DoAnBaseAcitvity{

	private TextView txtUserName;
	private TextView txtPassWord;
	public ArrayList<ClassStudent> listClass = new ArrayList<ClassStudent>();
	public ArrayList<Student> listStudent = new ArrayList<Student>();
	private CheckBox cbxRememberLogin;
	private ProgressDialog p;
	private ListClassDataSource databaseHelper;
	private ListStudentDataSource classHelper;
	private boolean isRemember = false;
	private Button btnLogin;
	private static int noClass = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);

		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			public void run() {
				
				boolean isLogined = pre.getBoolean(
						Constants.PREFERENCE_LOGGINED, false);
				boolean isRemember = pre.getBoolean(
						Constants.PREFERENCE_REMEMBER_LOGIN, false);
				if (isLogined && isRemember) {
					listClass = getListClassData( EncodeHelper.changeText(pre.getString(
							Constants.PREFERENCE_USER_NAME, "")));
					startApps();
//					showProgressDialog();
//					new Handler().postDelayed(new Runnable() {
//						@Override
//						public void run() {
//							
//							listClass = getListClassData( EncodeHelper.changeText(pre.getString(
//									Constants.PREFERENCE_USER_NAME, "")));
//							stopProgressDialog();
//							startApps();
//						}
//					}, 500);

				}else{
					setContentView(R.layout.layout_login);
					cbxRememberLogin = (CheckBox) findViewById(R.id.check_box_remember_login);
					btnLogin = ((Button) findViewById(R.id.btnsign_in));
					btnLogin.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							showProgressDialog();
							MainActivity.this.isRemember = cbxRememberLogin.isChecked();
							String userName = txtUserName.getText().toString();
							String passWord = txtPassWord.getText().toString();

							boolean isLoginned = pre.getBoolean(Constants.PREFERENCE_LOGGINED,
									false);

							if (isLoginned) {
								LoginOffline(userName, passWord);
							} else {
								if (isInternetAccess()) {
									LoginOnline(userName, passWord);
								} else {
									stopProgressDialog();
									Toast.makeText(MainActivity.this,
											getString(R.string.txt_internet_message),
											Toast.LENGTH_LONG).show();
								}
							}
						}
					});
					txtUserName = (TextView) findViewById(R.id.user_name);
					txtPassWord = (TextView) findViewById(R.id.pass_word);
					txtUserName.setText("2002013");
					txtPassWord.setText("2002013"); 
				}
			}
		}, 1000);
	}

	private ArrayList<ClassStudent> getListClassData(String userName) {
		databaseHelper = new ListClassDataSource(this, userName);
		databaseHelper.openForReadOnly();
		ArrayList<ClassStudent> res = (ArrayList<ClassStudent>) databaseHelper
				.getAllClass();
		//btnLogin.setEnabled(true);
		databaseHelper.close();
		return res;
	}

	private void saveListClassData(ArrayList<ClassStudent> list, String userName) {
		databaseHelper = new ListClassDataSource(this, userName);
		databaseHelper.open();
		for (ClassStudent cls : list) {
			databaseHelper.insertClass(cls);
		}
		databaseHelper.close();
	}

	private void showProgressDialog() {
		p = new ProgressDialog(MainActivity.this);
		p.setMessage(getString(R.string.txt_loading));
		p.setCancelable(false);
		p.show();
	}

	private void stopProgressDialog() {
		if (p != null && p.isShowing()) {
			p.dismiss();
			p = null;
		}
	}

	private void saveLoginData(String userName, String passWord) {
		userName = EncodeHelper.changeText(userName);
		passWord = EncodeHelper.changeText(passWord);
		pre.putString(Constants.PREFERENCE_USER_NAME, userName);
		pre.putString(Constants.PREFERENCE_PASS_WORD, passWord);
		pre.putBoolean(Constants.PREFERENCE_LOGGINED, true);
		pre.putBoolean(Constants.PREFERENCE_REMEMBER_LOGIN, true);
	}

	private void saveStudentData(ArrayList<Student> listStudent,
			String tableName) {
		classHelper = new ListStudentDataSource(this, tableName);
		classHelper.open();
		for (Student st : listStudent) {
			classHelper.insertStudent(st);
		}
		classHelper.close();
	}

	private void LoginOffline(final String userName, final String passWord) {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				String user = pre.getString(Constants.PREFERENCE_USER_NAME, "");
				String pass = pre.getString(Constants.PREFERENCE_PASS_WORD, "");

				if (pass.equals(EncodeHelper.changeText(passWord))
						&& user.equals(EncodeHelper.changeText(userName))) {
					listClass = getListClassData(userName);
					if (isRemember) {
						saveLoginData(userName, passWord);
					}
					stopProgressDialog();
					startApps();
				} else {
					Toast.makeText(MainActivity.this,
							getString(R.string.txt_login_offline_failed),
							Toast.LENGTH_LONG).show();
				}
			}
		}, 500);

	}

	private void LoginOnline(final String userName, final String passWord) {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				Logon logon = new Logon(Constants.LOGON_REQUEST,
						MainActivity.this, userName, passWord);
				getRequestQueue().addRequest(logon);
			}
		}, 500);

	}

	private void startApps() {
		Intent intent = new Intent(MainActivity.this, SlidingActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable(Constants.KEY_LIST_CLASS, listClass);
		intent.putExtras(bundle);
		startActivity(intent);
		finish();
	}
	

	// public void onCreateContextMenu(ContextMenu menu, View v,
	// ContextMenuInfo menuInfo) {
	// super.onCreateContextMenu(menu, v, menuInfo);
	// MenuInflater inflater = getMenuInflater();
	// inflater.inflate(R.menu.menu_class, menu);
	// }
	//
	// @Override
	// public boolean onContextItemSelected(MenuItem item) {
	// // AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
	// // .getMenuInfo();
	// switch (item.getItemId()) {
	// case R.id.lstsinhvien:
	// if (selectedClass >= 0 && selectedClass < listClass.size()) {
	// GetListStudent getList = new GetListStudent(listClass.get(
	// selectedClass).getMalop());
	// getList.execute();
	// }
	// return true;
	// case R.id.capnhat:
	// return true;
	// case R.id.diemdanh:
	// if (selectedClass >= 0 && selectedClass < listClass.size()) {
	// databaseHelper = new ClassDataSource(this, "tbl"
	// + listClass.get(selectedClass).getMalop());
	// databaseHelper.open();
	// BeginBarCodeScanner();
	// }
	// return true;
	// default:
	// return super.onContextItemSelected(item);
	//
	// }
	// }
	//

	class Logon extends RequestUI {
		private String meesage = getString(R.string.txt_login_online_failed);
		private String userName = "";
		private String passWord = "";
		private ListClassReturnObject list;

		public Logon(Object key, Activity activity, String userName,
				String passWord) {
			super(key, activity);
			this.userName = userName;
			this.passWord = passWord;
		}

		@Override
		public void execute() throws Exception {
			list = daApi.Login(userName, passWord);
		}

		@Override
		public void executeUI(Exception ex) {

			//btnLogin.setEnabled(true);
			if (list != null && list.getData() != null) {
				listClass = list.getData();
				for (ClassStudent cls : listClass) {
					ListStudent get = new ListStudent(
							Constants.LIST_STUDENT_REQUEST, MainActivity.this,
							cls.getMalop());
					getRequestQueue().addRequest(get);
				}
				meesage = list.getMessage();

				boolean isLogined = pre.getBoolean(
						Constants.PREFERENCE_LOGGINED, false);

				if (!isLogined) {
					saveListClassData(listClass, userName);
				}
				if (isRemember) {
					saveLoginData(userName, passWord);
				} else {
					pre.putBoolean(Constants.PREFERENCE_LOGGINED, true);
				}
				if (listClass.size() <= 0) {
					stopProgressDialog();
					startApps();
				}

			} else {
				stopProgressDialog();
				Toast.makeText(MainActivity.this, meesage, Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	class ListStudent extends RequestUI {
		private String meesage = getString(R.string.txt_get_list_student_failed);
		private String malop = "";
		private ListStudentReturnObject list;

		public ListStudent(Object key, Activity activity, String malop) {
			super(key, activity);
			this.malop = malop;
		}

		@Override
		public void execute() throws Exception {
			list = daApi.GetListStudent(malop);
		}

		@Override
		public void executeUI(Exception ex) {
			noClass++;

			//btnLogin.setEnabled(true);
			if (list != null) {
				listStudent = list.getData();

				meesage = list.getMessage();
				saveStudentData(listStudent, malop);
			} else {
				stopProgressDialog();
				Toast.makeText(MainActivity.this, meesage, Toast.LENGTH_LONG)
						.show();
			}
			if (noClass == listClass.size()) {
				stopProgressDialog();
				startApps();
			}
		}
	}
}
